
import store from "@/store"
import NProgress from "nprogress" // progress bar
import "nprogress/nprogress.css" // progress bar style
NProgress.configure({
  showSpinner: false // 是否显示右上角螺旋加载提示
})
async function beforeEach(to, from, next) {
  NProgress.start()
  if (to.name === "redirect") {
    //清除缓存
    await store.dispatch("tagsView/delCachedView", from)
  }
  const hasToken = store.getters.accessToken
  if (hasToken) {
    if (to.path === "/login") {
      NProgress.done()
      // if is logged in, redirect to the home page
      next({ name: "redirect", params: { path: "/" } })
      return
    } else {
      const hasGetUserInfo = store.getters.userInfo
      // 用户ID不等于 null 则代表有用户信息
      if (hasGetUserInfo.userId !== null) {
        NProgress.done()
        next()
      } else {
        //获取用户信息，动态加载菜单
        await store.dispatch("user/getUserInfo")
        NProgress.done()
        //如果单纯使用 next() 会导致刷新时 页面是空白页
        next({ ...to, replace: true })
      }
    }
  } else {
    if (to.meta && to.meta?.unNeedLogin) {
      NProgress.done()
      // in the free login whitelist, go directly
      next()
    } else {
      NProgress.done()
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`)
    }
  }
}
 
export default beforeEach
 